package cn.dglydrpy.study.j2ee.jdbc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.dbcp.BasicDataSource;
/*
 * Java 提供一套配置文件API, 可以解决软件的参数配置文件问题.
 * 使用加载properties配置文件和DBCP的方式进行封装,用于简化数据库编程
 */
public class DBUtil {
	
	private static String driverClass;
	private static String url;
	private static String username;
	private static String password;
	private static Integer initialSize;
	private static Integer maxActive;
	private static Integer maxIdle;

	private static BasicDataSource dataSource;
	
	private static AtomicInteger count = new AtomicInteger(0); //并发安全的int
	
	static{
		//创建属性对象
		Properties prop = new Properties();
		//通过反射得到文件的输入流
		String fileName = "jdbc.properties";
		//固定写法: 类名.class.getClassLoader().getResourceAsStream()
		InputStream ips = DBUtil.class.getClassLoader().getResourceAsStream(fileName);
		try {
			//把流交给属性对象
			prop.load(ips);
			//读取完毕就关闭流
			ips.close();
			//获取数据 获取到的数据类型为String
			driverClass = prop.getProperty("driverClass");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			initialSize = Integer.parseInt(prop.getProperty("initialSize"));
			maxActive = Integer.parseInt(prop.getProperty("maxActive"));
			maxIdle = Integer.parseInt(prop.getProperty("maxIdle")); 
			//连接池的操作***************
			//数据源对象
			dataSource = new BasicDataSource();
			//数据库连接信息
			dataSource.setDriverClassName(driverClass);
			dataSource.setUrl(url);
			dataSource.setUsername(username);
			dataSource.setPassword(password);
			//设置初始连接数量
			dataSource.setInitialSize(initialSize);
			//最大连接数量
			dataSource.setMaxActive(maxActive);
			//没连接时 最大空闲数量(处于不被销毁的待命状态)
			dataSource.setMaxIdle(maxIdle);
			//连接池的操作***************

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	//获取连接对象
	public static Connection getConn() throws Exception{
		System.out.println("已连接数据库:"+url.substring(0,url.lastIndexOf("?"))+",当前连接数:"+count.incrementAndGet());
		return dataSource.getConnection();
	}
	//关闭资源
	public static void close(Connection conn,Statement stat,ResultSet rs){
		try {
			if (rs!=null) {
				rs.close();
			}
			if (stat!=null) {
				stat.close();
			}
			if (conn!=null) {
				conn.setAutoCommit(true);//开启事务自动提交
				conn.close();
				System.out.println("当前连接数:"+count.decrementAndGet());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
